from flask import Blueprint, render_template, request, jsonify, redirect, url_for, session
from app.services.user_service import UserService
from flask_login import login_required, current_user

# 创建蓝图
users_admin_bp = Blueprint('users_admin', __name__, url_prefix='/admin/users')

# 管理员权限验证装饰器
def admin_required(view_func):
    def wrapped_view(*args, **kwargs):
        if not current_user.is_authenticated:
            return redirect(url_for('auth.login', next=request.url))
        
        if not current_user.is_admin:
            return jsonify({"success": False, "message": "需要管理员权限"}), 403
            
        return view_func(*args, **kwargs)
    wrapped_view.__name__ = view_func.__name__
    return wrapped_view

@users_admin_bp.route('/')
@admin_required
def index():
    """用户管理首页"""
    users = UserService.get_all_users()
    return render_template('admin/users.html', users=users)

@users_admin_bp.route('/create', methods=['POST'])
@admin_required
def create():
    """创建用户"""
    try:
        data = request.form
        # 基本验证
        if not data.get('name') or not data.get('password'):
            return jsonify({"success": False, "message": "用户名和密码不能为空"}), 400
            
        # 处理表单数据
        form_data = dict(data)
        
        # 处理复选框
        form_data['is_active'] = 'true' if data.get('is_active') == 'on' else 'false'
        form_data['is_admin'] = 'true' if data.get('is_admin') == 'on' else 'false'
            
        # 创建用户
        UserService.create_user(form_data)
        
        return jsonify({"success": True, "message": "用户创建成功"})
    except ValueError as e:
        return jsonify({"success": False, "message": str(e)}), 400
    except Exception as e:
        return jsonify({"success": False, "message": f"创建用户失败: {str(e)}"}), 500

@users_admin_bp.route('/update/<int:user_id>', methods=['POST'])
@admin_required
def update(user_id):
    """更新用户信息"""
    try:
        data = request.form
        
        # 处理表单数据
        form_data = dict(data)
        
        # 处理复选框
        form_data['is_active'] = 'true' if data.get('is_active') == 'on' else 'false'
        form_data['is_admin'] = 'true' if data.get('is_admin') == 'on' else 'false'
        
        # 更新用户
        UserService.update_user(user_id, form_data)
        
        return jsonify({"success": True, "message": "用户更新成功"})
    except ValueError as e:
        return jsonify({"success": False, "message": str(e)}), 404
    except Exception as e:
        return jsonify({"success": False, "message": f"更新用户失败: {str(e)}"}), 500

@users_admin_bp.route('/delete/<int:user_id>', methods=['POST'])
@admin_required
def delete(user_id):
    """删除用户"""
    try:
        # 删除用户
        UserService.delete_user(user_id)
        
        return jsonify({"success": True, "message": "用户删除成功"})
    except ValueError as e:
        return jsonify({"success": False, "message": str(e)}), 404
    except Exception as e:
        return jsonify({"success": False, "message": f"删除用户失败: {str(e)}"}), 500

@users_admin_bp.route('/get/<int:user_id>', methods=['GET'])
@admin_required
def get_user(user_id):
    """获取单个用户信息"""
    try:
        user = UserService.get_user_by_id(user_id)
        if not user:
            return jsonify({"success": False, "message": "用户不存在"}), 404
            
        return jsonify({
            "success": True,
            "user": user.to_dict()
        })
    except Exception as e:
        return jsonify({"success": False, "message": f"获取用户信息失败: {str(e)}"}), 500 